﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetfractionHub.Network.Protocol;
using NetfractionHub.Network.Protocol.BASE.Factory;
using Netfraction.Common.Logging;

namespace NetfractionHub.LocalMachine.BotCommands.Handler
{
    [CommandHandler("drop")]
    public class Drop : CommandHandler
    {
        public override BotReturnStatus HandleCommandMessage(NetfractionHub.RemoteMachine.Node source, CommandMessage message)
        {
            // A drop is just a kick without a reason or time...
            if (source == null)
                return new BotReturnStatus(false);

            string userToDrop = string.Empty;
            if (message.StringArguments.Count == 1)
                userToDrop = message.StringArguments.ContainsKey("user") ? message.StringArguments["user"] : string.Empty;
            else if (message.UnnamedArguments.Count == 1)
                userToDrop = message.UnnamedArguments[0];
            else
                return new BotReturnStatus(false, "Missing string parameter 'user'.");  // should reply with the help string for the function

            if (string.IsNullOrEmpty(userToDrop))
                return new BotReturnStatus(false, "Missing string parameter 'user'.");
              
            if (!Security.Permission.HasPermission(source.SecurityIdentity, typeof(Security.Permissions.DropIdentityPermission)))
                return new BotReturnStatus(false, Security.Permission.GetDeniedString(typeof(Security.Permissions.DropIdentityPermission)));

            RemoteMachine.Node nodeToDrop = Network.ConnectionManager.GetConnectedNodeByNickname(userToDrop);
            if (nodeToDrop == null)
                return new BotReturnStatus(false, string.Format("Cannot kick, the user '{0}' does not exist.", userToDrop));

            if (!Security.RoleManager.IsInAncestorTree(source.SecurityIdentity.Role, nodeToDrop.SecurityIdentity.Role))
                return new BotReturnStatus(false, string.Format("Permission denied. You are not an ancestor of user '{0}'.", userToDrop));

            string messageToRespond = string.Format("Dropping '{0}'.", userToDrop);

            LogManager.WriteEntry(messageToRespond, LogEventId.DropIdentity, LogLevel.Detailed);

            // should be sending a STA here...??? STA 32
            //nodeToKick.Connection.Disconnect();
            Network.ConnectionManager.KickNode(source, nodeToDrop, string.Empty, 90);
            
            return new BotReturnStatus(false);
        }
    }
}
